package org.example.cloudapply.repository;

import org.apache.ibatis.annotations.*;
import org.example.cloudapply.entity.ScheduleJob;

import java.util.List;

@Mapper
public interface ScheduleJobRepository {
    @Insert("INSERT INTO schedule_jobs (apply_id, job_type, trigger_time) " +
            "VALUES (#{applyId}, #{jobType}, #{triggerTime})")
    void createJob(ScheduleJob job);

    @Select("SELECT * FROM schedule_jobs WHERE status = 'pending' AND trigger_time <= NOW()")
    List<ScheduleJob> findPendingJobs();

    @Update("UPDATE schedule_jobs SET status = #{status} WHERE job_id = #{jobId}")
    void updateJobStatus(@Param("jobId") Integer jobId, @Param("status") String status);


    @Delete("DELETE FROM schedule_jobs WHERE apply_id = #{applyId}")
    int deleteByApplyId(Integer applyId);

    @Update("UPDATE schedule_jobs SET status = #{status} " +
            "WHERE apply_id = #{applyId} AND job_type = #{jobType}")
    ScheduleJob updateJobStatusByApplyId(
            @Param("applyId") Integer applyId,
            @Param("jobType") String jobType
    );

    @Select("SELECT sj.* FROM schedule_jobs sj " +
            "JOIN applications a ON sj.apply_id = a.apply_id " +
            "WHERE sj.status = 'pending' " +
            "AND a.status = 'approved' " +
            "AND sj.trigger_time <= NOW()")
    List<ScheduleJob> findPendingApprovedJobs();
}
